<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. MyBatis整合Spring所需的jar包如下：  Spring的jar包 Mybatis的jar包 Mybatis-Spring整合包，即mybatis-spring-1.3.2.jar MySql的数据库驱动jar包 数据库连接池的jar包">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaEE-Spring+Mybatis整合">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring+Mybatis整合/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. MyBatis整合Spring所需的jar包如下：  Spring的jar包 Mybatis的jar包 Mybatis-Spring整合包，即mybatis-spring-1.3.2.jar MySql的数据库驱动jar包 数据库连接池的jar包">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-fcae6251173f22a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-d058e1d6bbaaf92e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-bc6eba743d187817.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-4b8918a341059ec2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-72db446aa534dfd0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-8cad6fdd61c54851.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-91e8374cd8e83393.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-de414f379d05023c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-22f555a6f40383fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-4e752f78f507d4ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:51:31.801Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaEE-Spring+Mybatis整合">
<meta name="twitter:description" content="####1. MyBatis整合Spring所需的jar包如下：  Spring的jar包 Mybatis的jar包 Mybatis-Spring整合包，即mybatis-spring-1.3.2.jar MySql的数据库驱动jar包 数据库连接池的jar包">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-fcae6251173f22a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring+Mybatis整合/"/>





  <title>JavaEE-Spring+Mybatis整合 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring+Mybatis整合/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JavaEE-Spring+Mybatis整合</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. MyBatis整合Spring所需的jar包如下：</p>
<ul>
<li><a href="http://repo.springsource.org/libs-release-local/org/springframework/spring/" target="_blank" rel="noopener">Spring的jar包</a></li>
<li><a href="https://github.com/mybatis/mybatis-3" target="_blank" rel="noopener">Mybatis的jar包</a></li>
<li><a href="http://blog.mybatis.org/" target="_blank" rel="noopener">Mybatis-Spring整合包</a>，即mybatis-spring-1.3.2.jar</li>
<li><a href="https://www.mysql.com/products/connector/" target="_blank" rel="noopener">MySql的数据库驱动jar包</a></li>
<li><a href="http://commons.apache.org/" target="_blank" rel="noopener">数据库连接池的jar包</a><br><img src="https://upload-images.jianshu.io/upload_images/3110861-fcae6251173f22a0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></li>
</ul>
<a id="more"></a>
<p>####2.整合思路<br>MyBatis整合Spring的思路如下：</p>
<ul>
<li>SqlSessionFactory对象应该放到spring容器中作为单例存在。</li>
<li>传统Dao的开发方式中，应该从spring容器中获得sqlsession对象。</li>
<li>Mapper代理形式中，应该从spring容器中直接获得mapper的代理对象。</li>
<li>数据库的连接以及数据库连接池事务管理都交给spring容器来完成。<br>####3. 整合的步骤<br>下面我将按照下面整合的步骤来整合MyBatis与Spring：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">第一步：创建一个java工程。</span><br><span class="line">第二步：导入jar包（上面提到的jar包）。</span><br><span class="line">第三步：编写mybatis的配置文件——SqlMapConfig.xml。</span><br><span class="line">第四步：编写Spring的配置文件。 </span><br><span class="line">        1. 数据库连接及连接池</span><br><span class="line">        2.事务管理（暂时可以不配置）</span><br><span class="line">        3. sqlsessionFactory对象，配置到spring容器中</span><br><span class="line">        4. mapper代理对象或者是dao实现类配置到spring容器中</span><br><span class="line">第五步：编写Dao或者mapper.xml映射文件。</span><br><span class="line">第六步：测试。</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>####3. 创建工程，导入jar包<br><img src="https://upload-images.jianshu.io/upload_images/3110861-d058e1d6bbaaf92e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>####4. 创建配置文件</p>
<p>######1). 在工程下创建源码包config<br><img src="https://upload-images.jianshu.io/upload_images/3110861-bc6eba743d187817.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></p>
<p>######2). 在config下db.properties文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">jdbc.driver=com.mysql.jdbc.Driver</span><br><span class="line">jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8</span><br><span class="line">jdbc.username=root</span><br><span class="line">jdbc.password=root</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-4b8918a341059ec2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"></p>
<p>######3). 在config下创建spring包，并在spring包下创建application-context.xml配置文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot; xmlns:p=&quot;http://www.springframework.org/schema/p&quot;</span><br><span class="line">    xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot; xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans </span><br><span class="line">                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/context </span><br><span class="line">                        http://www.springframework.org/schema/context/spring-context-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/aop </span><br><span class="line">                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd </span><br><span class="line">                        http://www.springframework.org/schema/tx </span><br><span class="line">                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/util </span><br><span class="line">                        http://www.springframework.org/schema/util/spring-util-4.0.xsd&quot;&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;!-- 加载配置文件 --&gt;</span><br><span class="line">    &lt;context:property-placeholder location=&quot;classpath:db.properties&quot;/&gt; </span><br><span class="line">	&lt;!-- 数据库连接池 --&gt;                   </span><br><span class="line">	&lt;bean id=&quot;dataSource&quot; class=&quot;org.apache.commons.dbcp2.BasicDataSource&quot; destroy-method=&quot;close&quot;&gt;</span><br><span class="line">		&lt;property name=&quot;driverClassName&quot; value=&quot;$&#123;jdbc.driver&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;url&quot; value=&quot;$&#123;jdbc.url&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;username&quot; value=&quot;$&#123;jdbc.username&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;password&quot; value=&quot;$&#123;jdbc.password&#125;&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大连接数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxTotal&quot; value=&quot;10&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大空闲数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxIdle&quot; value=&quot;5&quot;/&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;!-- SqlSessionFactory的配置 --&gt;</span><br><span class="line">	&lt;bean id=&quot;sqlSessionFactory&quot; class=&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;&gt;</span><br><span class="line">		&lt;!-- 配置数据库连接池 --&gt;</span><br><span class="line">		&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;</span><br><span class="line">		&lt;!-- 加载Mybatis的核心配置文件 --&gt;</span><br><span class="line">		&lt;property name=&quot;configLocation&quot; value=&quot;classpath:mybatis/SqlMapConfig.xml&quot;&gt;&lt;/property&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>######4). 在config下创建mybatis包，并在mybatis包下创建SqlMapConfig.xml文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE configuration PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;</span><br><span class="line">&lt;configuration&gt;</span><br><span class="line">	&lt;!-- 配置pojo别名 --&gt;</span><br><span class="line">	&lt;typeAliases&gt;</span><br><span class="line">		&lt;!-- 扫描包的形式创建别名，别名就是类型，不区分大小写 --&gt;</span><br><span class="line">		&lt;!-- &lt;package name=&quot;xxx.xxx.xxx&quot;/&gt; --&gt;</span><br><span class="line">	&lt;/typeAliases&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 加载mapper文件 --&gt;</span><br><span class="line">	&lt;mappers&gt;</span><br><span class="line">		&lt;!-- 加载Mapper.xml文件，采用包加载 --&gt;</span><br><span class="line">		&lt;!-- &lt;package name=&quot;com.mazaiting.mapper&quot; /&gt; --&gt;</span><br><span class="line">	&lt;/mappers&gt;</span><br><span class="line">&lt;/configuration&gt;</span><br></pre></td></tr></table></figure></p>
<p>####5. Dao层的开发</p>
<ul>
<li><strong>传统Dao层的开发方式</strong></li>
<li><strong>使用mapper代理形式开发方式</strong></li>
<li><strong>使用扫描包配置mapper代理</strong><br>######1). 传统Dao层的开发方式<br>I. 在com.mazaiting.po包下创建User.java<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">public class User &#123;</span><br><span class="line">	private int id;</span><br><span class="line">	private String username;</span><br><span class="line">	private String sex;</span><br><span class="line">	private Date birthday;</span><br><span class="line">	private String address;</span><br><span class="line">	public int getId() &#123;</span><br><span class="line">		return id;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setId(int id) &#123;</span><br><span class="line">		this.id = id;</span><br><span class="line">	&#125;</span><br><span class="line">	public String getUsername() &#123;</span><br><span class="line">		return username;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setUsername(String username) &#123;</span><br><span class="line">		this.username = username;</span><br><span class="line">	&#125;</span><br><span class="line">	public String getSex() &#123;</span><br><span class="line">		return sex;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setSex(String sex) &#123;</span><br><span class="line">		this.sex = sex;</span><br><span class="line">	&#125;</span><br><span class="line">	public Date getBirthday() &#123;</span><br><span class="line">		return birthday;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setBirthday(Date birthday) &#123;</span><br><span class="line">		this.birthday = birthday;</span><br><span class="line">	&#125;</span><br><span class="line">	public String getAddress() &#123;</span><br><span class="line">		return address;</span><br><span class="line">	&#125;</span><br><span class="line">	public void setAddress(String address) &#123;</span><br><span class="line">		this.address = address;</span><br><span class="line">	&#125;</span><br><span class="line">	@Override</span><br><span class="line">	public String toString() &#123;</span><br><span class="line">		return &quot;User [id=&quot; + id + &quot;, username=&quot; + username + &quot;, sex=&quot; + sex + &quot;, birthday=&quot; + birthday + &quot;, address=&quot;</span><br><span class="line">				+ address + &quot;]&quot;;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>II. 修改SqlMapConfig.xml文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE configuration PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-config.dtd&quot;&gt;</span><br><span class="line">&lt;configuration&gt;</span><br><span class="line">	&lt;!-- 配置pojo别名 --&gt;</span><br><span class="line">	&lt;typeAliases&gt;</span><br><span class="line">		&lt;!-- 扫描包的形式创建别名，别名就是类型，不区分大小写 --&gt;</span><br><span class="line">		&lt;!-- &lt;package name=&quot;xxx.xxx.xxx&quot;/&gt; --&gt;</span><br><span class="line">		&lt;package name=&quot;com.mazaiting.po&quot;/&gt;</span><br><span class="line">	&lt;/typeAliases&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 加载mapper文件 --&gt;</span><br><span class="line">	&lt;mappers&gt;</span><br><span class="line">		&lt;!-- resource是基于classpath来加载的 --&gt;</span><br><span class="line">		&lt;mapper resource=&quot;sqlmap/user.xml&quot;/&gt;</span><br><span class="line">		&lt;!-- 加载Mapper.xml文件，采用包加载 --&gt;</span><br><span class="line">		&lt;!-- &lt;package name=&quot;com.mazaiting.mapper&quot; /&gt; --&gt;	</span><br><span class="line">	&lt;/mappers&gt;</span><br><span class="line">&lt;/configuration&gt;</span><br></pre></td></tr></table></figure></p>
<p>III. 在config包下创建sqlmap包，并在sqlmap包下创建user.xml文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;test&quot;&gt;</span><br><span class="line">	&lt;select id=&quot;getUserById&quot; parameterType=&quot;int&quot; resultType=&quot;user&quot;&gt;</span><br><span class="line">		select * from user where id = #&#123;id&#125;</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;select id=&quot;getUserByName&quot; parameterType=&quot;string&quot; resultType=&quot;user&quot;&gt;</span><br><span class="line">		select * from user where username like &apos;%$&#123;value&#125;%&apos;</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;select id=&quot;addUser&quot; parameterType=&quot;user&quot;&gt;</span><br><span class="line">		insert into user(username, birthday,sex,address)</span><br><span class="line">		values(#&#123;username&#125;,#&#123;birthday&#125;,#&#123;sex&#125;,#&#123;address&#125;)</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p>IV. 在com.mazaiting.dao包下创建User接口<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public interface UserDao &#123;</span><br><span class="line">	User getUserById(int id);</span><br><span class="line">	List&lt;User&gt; getUserByName(String username);</span><br><span class="line">	void addUser(User user);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>V. 在com.mazaiting.dao.impl下创建实现UserDao接口和继承SqlsessionDaoSupport的类UserDaoImpl<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao &#123;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public User getUserById(int id) &#123;</span><br><span class="line">		SqlSession session = getSqlSession();</span><br><span class="line">		User user = session.selectOne(&quot;getUserById&quot;, 10);</span><br><span class="line">		return user;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public List&lt;User&gt; getUserByName(String username) &#123;</span><br><span class="line">		SqlSession session = getSqlSession();</span><br><span class="line">		List&lt;User&gt; list = session.selectList(&quot;getUserByName&quot;, &quot;张&quot;);</span><br><span class="line">		return list;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public void addUser(User user) &#123;</span><br><span class="line">		SqlSession session = getSqlSession();</span><br><span class="line">		session.insert(&quot;addUser&quot;, user);</span><br><span class="line">		 // 提交事务</span><br><span class="line">		session.commit();</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>注意：以上每个方法中不要手动关闭SqlSession，如果你手动关闭了，就会抛出一个异常。</strong><br>VI. 在application-context.xml文件中配置UserDaoImpl<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot; xmlns:p=&quot;http://www.springframework.org/schema/p&quot;</span><br><span class="line">    xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot; xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans </span><br><span class="line">                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/context </span><br><span class="line">                        http://www.springframework.org/schema/context/spring-context-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/aop </span><br><span class="line">                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd </span><br><span class="line">                        http://www.springframework.org/schema/tx </span><br><span class="line">                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/util </span><br><span class="line">                        http://www.springframework.org/schema/util/spring-util-4.0.xsd&quot;&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;!-- 加载配置文件 --&gt;</span><br><span class="line">    &lt;context:property-placeholder location=&quot;classpath:db.properties&quot;/&gt; </span><br><span class="line">	&lt;!-- 数据库连接池 --&gt;                   </span><br><span class="line">	&lt;bean id=&quot;dataSource&quot; class=&quot;org.apache.commons.dbcp2.BasicDataSource&quot; destroy-method=&quot;close&quot;&gt;</span><br><span class="line">		&lt;property name=&quot;driverClassName&quot; value=&quot;$&#123;jdbc.driver&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;url&quot; value=&quot;$&#123;jdbc.url&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;username&quot; value=&quot;$&#123;jdbc.username&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;password&quot; value=&quot;$&#123;jdbc.password&#125;&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大连接数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxTotal&quot; value=&quot;10&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大空闲数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxIdle&quot; value=&quot;5&quot;/&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;!-- SqlSessionFactory的配置 --&gt;</span><br><span class="line">	&lt;bean id=&quot;sqlSessionFactory&quot; class=&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;&gt;</span><br><span class="line">		&lt;!-- 配置数据库连接池 --&gt;</span><br><span class="line">		&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;</span><br><span class="line">		&lt;!-- 加载Mybatis的核心配置文件 --&gt;</span><br><span class="line">		&lt;property name=&quot;configLocation&quot; value=&quot;classpath:mybatis/SqlMapConfig.xml&quot;&gt;&lt;/property&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;bean id=&quot;userDaoImpl&quot; class=&quot;com.mazaiting.dao.impl.UserDaoImpl&quot;&gt;</span><br><span class="line">		&lt;property name=&quot;sqlSessionFactory&quot; ref=&quot;sqlSessionFactory&quot;&gt;&lt;/property&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>VII. 在工程路径下创建test源码包，并创建对应包下的测试类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public class UserDaoTest &#123;</span><br><span class="line">	private ApplicationContext context;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init()&#123;</span><br><span class="line">		// 初始化Spring容器</span><br><span class="line">		context = new ClassPathXmlApplicationContext(&quot;classpath:spring/application-context.xml&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void testGetUserById()&#123;</span><br><span class="line">		// 通过类型装配</span><br><span class="line">		UserDao dao = context.getBean(UserDao.class);</span><br><span class="line">		User user = dao.getUserById(24);</span><br><span class="line">		System.out.println(user);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>VIII. 打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-72db446aa534dfd0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"></p>
<p>VIIII. 如果getUserById的方法中手动关闭session, 则会抛出java.lang.UnsupportedOperationException: Manual close is not allowed over a Spring managed SqlSession异常。<strong>因此在方法中一定不能调用<code>session.close()</code>方法。</strong><br><img src="https://upload-images.jianshu.io/upload_images/3110861-8cad6fdd61c54851.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"></p>
<p>######2). 使用mapper代理形式开发方式<br>I. 创建一个UserMapper接口<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public interface UserMapper &#123;</span><br><span class="line">	User getUserById(int id);</span><br><span class="line">	List&lt;User&gt; getUserByName(String username);</span><br><span class="line">	void addUser(User user);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>II. 创建UserMapper.xml文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE mapper PUBLIC &quot;-//mybatis.org//DTD Mapper 3.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-3-mapper.dtd&quot;&gt;</span><br><span class="line">&lt;mapper namespace=&quot;com.mazaiting.mapper.UserMapper&quot;&gt;</span><br><span class="line">	&lt;select id=&quot;getUserById&quot; parameterType=&quot;int&quot; resultType=&quot;user&quot;&gt;</span><br><span class="line">		select * from user where id = #&#123;id&#125;</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;select id=&quot;getUserByName&quot; parameterType=&quot;string&quot; resultType=&quot;user&quot;&gt;</span><br><span class="line">		select * from user where username like &apos;%$&#123;value&#125;%&apos;</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;select id=&quot;addUser&quot; parameterType=&quot;user&quot;&gt;</span><br><span class="line">		insert into user(username, birthday,sex,address)</span><br><span class="line">		values(#&#123;username&#125;,#&#123;birthday&#125;,#&#123;sex&#125;,#&#123;address&#125;)</span><br><span class="line">	&lt;/select&gt;</span><br><span class="line">&lt;/mapper&gt;</span><br></pre></td></tr></table></figure></p>
<p>III. 在application-context.xml文件中配置Mapper代理<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot; xmlns:p=&quot;http://www.springframework.org/schema/p&quot;</span><br><span class="line">    xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot; xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans </span><br><span class="line">                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/context </span><br><span class="line">                        http://www.springframework.org/schema/context/spring-context-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/aop </span><br><span class="line">                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd </span><br><span class="line">                        http://www.springframework.org/schema/tx </span><br><span class="line">                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/util </span><br><span class="line">                        http://www.springframework.org/schema/util/spring-util-4.0.xsd&quot;&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;!-- 加载配置文件 --&gt;</span><br><span class="line">    &lt;context:property-placeholder location=&quot;classpath:db.properties&quot;/&gt; </span><br><span class="line">	&lt;!-- 数据库连接池 --&gt;                   </span><br><span class="line">	&lt;bean id=&quot;dataSource&quot; class=&quot;org.apache.commons.dbcp2.BasicDataSource&quot; destroy-method=&quot;close&quot;&gt;</span><br><span class="line">		&lt;property name=&quot;driverClassName&quot; value=&quot;$&#123;jdbc.driver&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;url&quot; value=&quot;$&#123;jdbc.url&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;username&quot; value=&quot;$&#123;jdbc.username&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;password&quot; value=&quot;$&#123;jdbc.password&#125;&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大连接数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxTotal&quot; value=&quot;10&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大空闲数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxIdle&quot; value=&quot;5&quot;/&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;!-- SqlSessionFactory的配置 --&gt;</span><br><span class="line">	&lt;bean id=&quot;sqlSessionFactory&quot; class=&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;&gt;</span><br><span class="line">		&lt;!-- 配置数据库连接池 --&gt;</span><br><span class="line">		&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;</span><br><span class="line">		&lt;!-- 加载Mybatis的核心配置文件 --&gt;</span><br><span class="line">		&lt;property name=&quot;configLocation&quot; value=&quot;classpath:mybatis/SqlMapConfig.xml&quot;&gt;&lt;/property&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line"></span><br><span class="line">	&lt;!-- 配置代理对象 --&gt;</span><br><span class="line">	&lt;bean id=&quot;userMapper&quot; class=&quot;org.mybatis.spring.mapper.MapperFactoryBean&quot;&gt;</span><br><span class="line">		&lt;!-- 设置代理的mapper接口，即为哪一个类创建代理对象 --&gt;</span><br><span class="line">		&lt;property name=&quot;mapperInterface&quot; value=&quot;com.mazaiting.mapper.UserMapper&quot;&gt;&lt;/property&gt;</span><br><span class="line">		&lt;!-- 由于MapperFactoryBean类继承自SqlSessionDaoSupport类，所以注入SqlSessionFactory类 --&gt;</span><br><span class="line">		&lt;property name=&quot;sqlSessionFactory&quot; ref=&quot;sqlSessionFactory&quot;&gt;&lt;/property&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p>IV. 测试类<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">public class UserMapperTest &#123;</span><br><span class="line"></span><br><span class="line">	ApplicationContext context;</span><br><span class="line">	</span><br><span class="line">	@Before</span><br><span class="line">	public void init() &#123;</span><br><span class="line">		context = new ClassPathXmlApplicationContext(&quot;classpath:spring/application-context.xml&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Test</span><br><span class="line">	public void testGetUserById() &#123;</span><br><span class="line">		UserMapper mapper = context.getBean(UserMapper.class);</span><br><span class="line">		User user = mapper.getUserById(24);</span><br><span class="line">		System.out.println(user.toString());</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>V. 打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-91e8374cd8e83393.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>######3). 使用扫描包配置mapper代理<br>I. 在application-context.xml文件中配置一个包扫描器<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;</span><br><span class="line">    xmlns:context=&quot;http://www.springframework.org/schema/context&quot; xmlns:p=&quot;http://www.springframework.org/schema/p&quot;</span><br><span class="line">    xmlns:aop=&quot;http://www.springframework.org/schema/aop&quot; xmlns:tx=&quot;http://www.springframework.org/schema/tx&quot;</span><br><span class="line">    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span><br><span class="line">    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans </span><br><span class="line">                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/context </span><br><span class="line">                        http://www.springframework.org/schema/context/spring-context-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/aop </span><br><span class="line">                        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd </span><br><span class="line">                        http://www.springframework.org/schema/tx </span><br><span class="line">                        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd</span><br><span class="line">                        http://www.springframework.org/schema/util </span><br><span class="line">                        http://www.springframework.org/schema/util/spring-util-4.0.xsd&quot;&gt;</span><br><span class="line">    </span><br><span class="line">    &lt;!-- 加载配置文件 --&gt;</span><br><span class="line">    &lt;context:property-placeholder location=&quot;classpath:db.properties&quot;/&gt; </span><br><span class="line">	&lt;!-- 数据库连接池 --&gt;                   </span><br><span class="line">	&lt;bean id=&quot;dataSource&quot; class=&quot;org.apache.commons.dbcp2.BasicDataSource&quot; destroy-method=&quot;close&quot;&gt;</span><br><span class="line">		&lt;property name=&quot;driverClassName&quot; value=&quot;$&#123;jdbc.driver&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;url&quot; value=&quot;$&#123;jdbc.url&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;username&quot; value=&quot;$&#123;jdbc.username&#125;&quot;/&gt;</span><br><span class="line">		&lt;property name=&quot;password&quot; value=&quot;$&#123;jdbc.password&#125;&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大连接数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxTotal&quot; value=&quot;10&quot;/&gt;</span><br><span class="line">		&lt;!-- 设置最大空闲数 --&gt;</span><br><span class="line">		&lt;property name=&quot;maxIdle&quot; value=&quot;5&quot;/&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;!-- SqlSessionFactory的配置 --&gt;</span><br><span class="line">	&lt;bean id=&quot;sqlSessionFactory&quot; class=&quot;org.mybatis.spring.SqlSessionFactoryBean&quot;&gt;</span><br><span class="line">		&lt;!-- 配置数据库连接池 --&gt;</span><br><span class="line">		&lt;property name=&quot;dataSource&quot; ref=&quot;dataSource&quot;/&gt;</span><br><span class="line">		&lt;!-- 加载Mybatis的核心配置文件 --&gt;</span><br><span class="line">		&lt;property name=&quot;configLocation&quot; value=&quot;classpath:mybatis/SqlMapConfig.xml&quot;&gt;&lt;/property&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">	</span><br><span class="line">	&lt;!-- 配置包扫描器 --&gt;</span><br><span class="line">	&lt;bean class=&quot;org.mybatis.spring.mapper.MapperScannerConfigurer&quot;&gt;</span><br><span class="line">		&lt;!-- 配置要扫描的包 --&gt;</span><br><span class="line">		&lt;property name=&quot;basePackage&quot; value=&quot;com.mazaiting.mapper&quot;/&gt;</span><br><span class="line">	&lt;/bean&gt;</span><br><span class="line">&lt;/beans&gt;</span><br></pre></td></tr></table></figure></p>
<p><strong>注意：</strong></p>
<ul>
<li>该扫描器会自动去Spring容器中去找你已经初始化好后的sqlSessionFactory， 所以在此并不需要配置。</li>
<li>如果要扫描多个包，那么使用半角逗号分隔。</li>
<li>使用扫描包的形式配置mapper代理之后，每个mapper代理对象的id就是类名，且首字母小写。</li>
</ul>
<p><strong>特别注意：</strong><br>如果在application-context.xml文件中配置了扫描包之后，在SqlMapConfig.xml配置文件中就不需要以下配置了：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 加载mapper文件 --&gt;</span><br><span class="line">&lt;mappers&gt;</span><br><span class="line">    &lt;!-- resource是基于classpath来加载的 --&gt;</span><br><span class="line">    &lt;mapper resource=&quot;sqlmap/user.xml&quot; /&gt;</span><br><span class="line">&lt;/mappers&gt;</span><br></pre></td></tr></table></figure></p>
<p>II. 测试testGetUserById方法结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-de414f379d05023c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>
<p>####6. <a href="http://blog.mybatis.org/" target="_blank" rel="noopener">逆向工程</a><br>MyBatis的一个主要的特点就是需要程序员自己编写sql，那么如果表太多的话，难免会很麻烦，所以mybatis官方提供了一个逆向工程，可以针对单表自动生成mybatis执行所需要的代码（包括mapper.xml、mapper.java、po..）。一般在开发中，常用的逆向工程方式是通过数据库的表生成代码。</p>
<p>######1). 工具包<br>使用MyBatis的逆向工程，需要导入逆向工程的jar包<a href="https://github.com/mybatis/generator/releases/tag/mybatis-generator-1.3.6" target="_blank" rel="noopener">mybatis-generator-core-1.3.6.jar</a><br><img src="https://upload-images.jianshu.io/upload_images/3110861-22f555a6f40383fa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图9.png"></p>
<p>######2). 新建工程(切勿在原项目中使用)<br>I. 配置generatorConfig.xml文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span><br><span class="line">&lt;!DOCTYPE generatorConfiguration PUBLIC &quot;-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN&quot; &quot;http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd&quot;&gt;</span><br><span class="line">&lt;generatorConfiguration&gt;</span><br><span class="line">	&lt;context id=&quot;testTables&quot; targetRuntime=&quot;MyBatis3&quot;&gt;</span><br><span class="line">		&lt;commentGenerator&gt;</span><br><span class="line">			&lt;!-- 是否去除自动生成的注释 true是，false否 --&gt;</span><br><span class="line">			&lt;property name=&quot;suppressAllComments&quot; value=&quot;true&quot;/&gt;</span><br><span class="line">		&lt;/commentGenerator&gt;</span><br><span class="line">		&lt;!-- 数据库连接信息：驱动类、连接地址、用户名、密码 --&gt;</span><br><span class="line">		&lt;jdbcConnection </span><br><span class="line">			driverClass=&quot;com.mysql.jdbc.Driver&quot; </span><br><span class="line">			connectionURL=&quot;jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&quot;</span><br><span class="line">			userId=&quot;root&quot; password=&quot;root&quot;/&gt;</span><br><span class="line">		&lt;!-- 默认false，把JDBC DECIMAL 和 NUMBERIC类型解析为Integer；</span><br><span class="line">			为true时把JDBC DECIMAL和NUMBERIC类型解析为java.math.BigDecimal	</span><br><span class="line">		--&gt;</span><br><span class="line">		&lt;javaTypeResolver&gt;</span><br><span class="line">			&lt;property name=&quot;forceBigDecimals&quot; value=&quot;false&quot;/&gt;</span><br><span class="line">		&lt;/javaTypeResolver&gt;</span><br><span class="line">		&lt;!-- targetProject:生成PO类型的位置 --&gt;</span><br><span class="line">		&lt;javaModelGenerator </span><br><span class="line">			targetPackage=&quot;com.mazaiting.po&quot;</span><br><span class="line">			targetProject=&quot;.\src&quot;&gt;</span><br><span class="line">			&lt;!-- enableSubPackages是否让schema作为包的后缀 --&gt;</span><br><span class="line">			&lt;property name=&quot;enableSubPackages&quot; value=&quot;false&quot;/&gt;</span><br><span class="line">			&lt;!-- 从数据库返回的值被清理前后的空格 --&gt;</span><br><span class="line">			&lt;property name=&quot;trimStrings&quot; value=&quot;true&quot;/&gt;</span><br><span class="line">		&lt;/javaModelGenerator&gt;</span><br><span class="line">		&lt;!-- targetProject:mapper映射文件生成的位置 --&gt;</span><br><span class="line">		&lt;sqlMapGenerator </span><br><span class="line">			targetPackage=&quot;com.mazaiting.mapper&quot;</span><br><span class="line">			targetProject=&quot;.\src&quot;&gt;</span><br><span class="line">			&lt;!-- enableSubPackages:是否让schema作为包的后缀 --&gt;</span><br><span class="line">			&lt;property name=&quot;enableSubPackages&quot; value=&quot;false&quot;/&gt;</span><br><span class="line">		&lt;/sqlMapGenerator&gt;</span><br><span class="line">		&lt;!-- targetPackage: mapper接口生成的位置 --&gt;</span><br><span class="line">		&lt;javaClientGenerator </span><br><span class="line">			targetPackage=&quot;com.mazaiting.mapper&quot;</span><br><span class="line">			type=&quot;XMLMAPPER&quot;</span><br><span class="line">			targetProject=&quot;.\src&quot;&gt;</span><br><span class="line">			&lt;!-- enableSubPackages：是否让schema作为包的后缀 --&gt;</span><br><span class="line">			&lt;property name=&quot;enableSubPackages&quot; value=&quot;false&quot;/&gt;	</span><br><span class="line">		&lt;/javaClientGenerator&gt;</span><br><span class="line">		&lt;!-- 指定数据库表 --&gt;</span><br><span class="line">		&lt;table tableName=&quot;user&quot;/&gt;</span><br><span class="line">		&lt;table tableName=&quot;orders&quot;/&gt;</span><br><span class="line">		</span><br><span class="line">		&lt;!-- 有些表的字段需要指定java类型</span><br><span class="line">         &lt;table schema=&quot;&quot; tableName=&quot;&quot;&gt;</span><br><span class="line">            &lt;columnOverride column=&quot;&quot; javaType=&quot;&quot; /&gt;</span><br><span class="line">        &lt;/table&gt; --&gt;</span><br><span class="line">	&lt;/context&gt;</span><br><span class="line">&lt;/generatorConfiguration&gt;</span><br></pre></td></tr></table></figure></p>
<p>II. 在src目录下创建log4j.properties文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># Global logging configuration</span><br><span class="line">log4j.rootLogger=DEBUG, stdout</span><br><span class="line"># Console output...</span><br><span class="line">log4j.appender.stdout=org.apache.log4j.ConsoleAppender</span><br><span class="line">log4j.appender.stdout.layout=org.apache.log4j.PatternLayout</span><br><span class="line">log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n</span><br></pre></td></tr></table></figure></p>
<p>III. 创建生成代码<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">public class GeneratorSqlmap &#123;</span><br><span class="line">	public static void main(String[] args) throws Exception &#123;</span><br><span class="line">		List&lt;String&gt; warnings = new ArrayList&lt;&gt;();</span><br><span class="line">		boolean overwrite = true;</span><br><span class="line">		// 指定逆向工程配置文件</span><br><span class="line">		File configFile = new File(&quot;generatorConfig.xml&quot;);</span><br><span class="line">		ConfigurationParser cParser = new ConfigurationParser(warnings);</span><br><span class="line">		Configuration config = cParser.parseConfiguration(configFile);</span><br><span class="line">		DefaultShellCallback callback = new DefaultShellCallback(overwrite);</span><br><span class="line">		MyBatisGenerator generator = new MyBatisGenerator(config, callback, warnings);</span><br><span class="line">		generator.generate(null);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>IV. 运行后刷新项目<br><img src="https://upload-images.jianshu.io/upload_images/3110861-4e752f78f507d4ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图10.png"></p>
<p>###<a href="https://download.csdn.net/download/mazaiting/10352115" target="_blank" rel="noopener">代码下载</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JavaEE-Mybatis使用/" rel="next" title="JavaEE-Mybatis使用">
                <i class="fa fa-chevron-left"></i> JavaEE-Mybatis使用
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JavaEE-Spring-AOP使用/" rel="prev" title="JavaEE-Spring-AOP使用">
                JavaEE-Spring-AOP使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
